<template>
  <div class="deploy">
    <div class="cardTop">部署模型</div>
    <el-card class="elCard">
      <div class="left">
        <ul class="leftUl">
          <li :class="changeClass">
            <div class="circle">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
            <div class="text">基础信息</div>
          </li>
          <li class="leftLi2">
            <div class="circle">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
            <div class="text">高级配置</div>
            <div class="textBottom" @click="mouseupHandle()">
              <img :src="isCreate ? xiala2 : xiala" alt="" />
              选填
            </div>
          </li>
          <li class="leftLi3" :class="changeClass">
            <div class="circle3">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
          </li>
        </ul>
      </div>
      <div
        class="elForm"
        v-loading="loading"
        element-loading-text="极速生成中..."
        :element-loading-spinner="svg"
        element-loading-svg-view-box="-10, -10, 50, 50"
        style="width: 1000px"
      >
        <el-form :model="form" :rules="rules" label-width="120px" ref="formRef">
          <el-form-item label="模型名" prop="cont_name">
            <el-input v-model="form.cont_name" />
          </el-form-item>

          <el-form-item label="从图中选择镜像" prop="image">
            <el-input v-model="selectedOption" />
          </el-form-item>

          <div class="echarts">
            <div id="myEcharts"></div>
          </div>

          <el-form-item label="选择模型" prop="model" class="selectModel">
            <el-select v-model="form.model" placeholder="请选择一个模型">
              <el-option
                v-for="(item, index) in modelList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <!-- 高级选项 -->
          <div class="high" v-if="isHighShow">
            <el-form-item label="主机端口">
              <el-input v-model="form.local_port" />
            </el-form-item>
            <el-form-item label="服务端口">
              <el-input v-model="form.server_port" />
            </el-form-item>
            <el-form-item label="工作台端口">
              <el-input v-model="form.worker_port" />
            </el-form-item>
          </div>
          <el-form-item class="elButton">
            <el-button type="primary" @click="onSubmit">创建模型</el-button>
            <el-button @click="cancel">取消创建</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElUpload,
  ElSelect,
  ElOption,
  ElMessage,
  ElLoading,
  ElCard
} from 'element-plus'
import { ref, reactive, computed, onUnmounted, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { beginDeploy } from '../../api/model.js'
import xiala2 from '../../assets/image/上拉.png'
import xiala from '../../assets/image/下拉.png'
import { useRouter } from 'vue-router'
const router = useRouter()
const loading = ref(false)
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 3px; fill: rgba(0, 0, 0, 0)"/>      `
const formRef = ref(null)
const form = ref({
  cont_name: '',
  image: '',
  model: '',
  workmode: ''
})
const modelList = ref([
  'agi ui',
  'autogen',
  'bert-base-chinese',
  'ChatGLM2-6B',
  'chatglm2-6b-32k',
  'internlm-chat-7b-8k',
  'lang_output',
  'langport',
  'langport_logs',
  'LocalAI',
  'logs',
  'mambaforge',
  'ningyu-spring-15b-v1.0-fp16',
  'openbuddy-3@b-v1.3-ggml',
  'openbuddy-30b-v7.1-bf16',
  'openbuddy-7b-v4',
  'openbuddy-f-7b-v6-bf16',
  'openbuddy-ggm1-30b-v1.3',
  'openbuddy-llama2-13b-v8.1-fp16',
  'openbuddy-lamacpp-13b-v5-q5',
  'openbuddy-mistral-7b-v13.1',
  'openbuddy-openllama-13b-v7-fp16',
  'openbuddy-openllama-7b-v12-bf16',
  'openbuddy-openllama-7b-v5-fp16',
  'openbuddy-zephyr-7b-V14.1',
  'pro-langport',
  'sentence-bert',
  'snap',
  'test4newname',
  'UIE'
])
const imageList = ref(['langport0.6', 'llama0.7'])
let chartInstance = null
const selectedOption = ref('')
const isHighShow = ref(false) // 高级配置显示
const isCreate = ref(false) // 下拉图片切换

//高级配置 显示事件
const mouseupHandle = () => {
  isCreate.value = !isCreate.value
  isHighShow.value = !isHighShow.value
}

//高级配置 样式更改
const changeClass = computed(() => {
  if (isCreate.value) {
    return 'leftLi isCreateTrue'
  } else {
    return 'leftLi'
  }
})

const cancel = () => {
  router.push('./')
}

const rules = reactive({
  cont_name: [
    { required: true, message: '请输入正确的英文名字', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/,
      message: '英文名字格式错误 支持英文+数字',
      trigger: 'blur'
    }
  ],
  image: [
    {
      required: true,
      message: '请从下图中选择镜像地址',
      trigger: 'blur',
      validator: validateImage
    }
  ],
  model: [{ required: true, message: '请选择正确的模型', trigger: 'blur' }],
  workmode: [{ required: true, message: '请选择一个工作环境', trigger: 'blur' }]
})

// 有值时直接通过
function validateImage (rule, value, callback) {
  if (selectedOption.value) {
    // 有值时直接通过验证
    callback()
  } else {
    // 没有值时显示错误信息
    callback(new Error('请从下图中选择镜像地址'))
  }
}

function initChart () {
  const chartDom = document.getElementById('myEcharts')
  let chartInstance = echarts.init(chartDom)

  // 根据imageList数组生成series中的data数据
  const echartsDataList = imageList.value.map((name, index) => {
    return {
      value: Math.floor(100 / imageList.value.length),
      name: name
    }
  })

  // 把配置和数据放这里
  chartInstance.setOption({
    color: ['#0099FF', '#00FF00'],
    title: {
      show: true,
      text: '镜像地址',
      top: 'middle',
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#27264d'
      }
    },
    tooltip: {
      trigger: 'item',
      extraCssText: 'box-shadow: 0 0 3px rgba(100, 100, 100, 0.8)',
      formatter: function (params) {
        return `<div style="display: flex; align-items: center;">
                <div style="width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 10px;"></div>
                镜像地址 : ${params.name}
              </div>`
      }
    },
    series: [
      {
        name: '镜像地址',
        type: 'pie',
        radius: ['95%', '55%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 15,
          borderColor: 'rgba(200,200,200,0.3)',
          borderWidth: 0,
          shadowColor: 'rgba(200, 200, 200, 0.5)',
          shadowBlur: 5
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: false,
            fontSize: '30',
            fontWeight: 'normal'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 782, name: 'langport0.6' },
          { value: 218, name: 'llama0.7' }
        ]
      }
    ]
  })
  chartInstance.on('click', params => {
    selectedOption.value = params.name
  })

  window.onresize = function () {
    //自适应大小
    chartInstance.resize()
  }
}

onMounted(() => {
  initChart()
})

// 关闭echarts时销毁实例
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})

const onSubmit = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    loading.value = true
    let msgData = {
      imgname: selectedOption.value,
      cont_name: form.value.cont_name,
      model_path: `/nvme1/${modelList.value}`,
      // model_path: '/nvme1/ningyu',
      model_name: 'aa',
      workmode: form.workmode === '0' ? '0' : '1',
      docker_ports: '8002',
      local_ports: '8002',
      net_name: 'test4lang',
      ctrad: '21001',
      logs_path: '/nvme1/ningyu/langport_logs'
    }
    console.log('创建新容器之前提交的数据', msgData)
    beginDeploy(msgData)
      .then(res => {
        loading.value = false

        // 处理请求成功的响应
        console.log('res', res)

        ElMessage({
          showClose: true,
          message: '创建成功 训练或部署 让数据更严谨吧~',
          type: 'success'
        })
        router.push('./drill')

        if (res.msg === 'build failed') {
          ElMessage({
            showClose: true,
            message: '模型名重复 请设置一个新的模型名',
            type: 'info'
          })
        }
      })
      .catch(error => {
        loading.value = false
        // 处理请求错误
        console.error(error)
      })

    console.log('提交了表单')
  } else {
    console.log('表单数据不完整')
  }
  // })
}
</script>

<style lang="less" scoped>
.deploy {
  padding: 30px 60px 0 60px;

  .cardTop {
    margin-bottom: 30px;
    color: #27264d;
    font-size: 32px;
    opacity: 0.85;
    display: flex;
  }
  .elCard {
    .left {
      width: 300px;
      .leftUl {
        img {
          width: 20px;
          height: 20px;
        }
        .text {
          margin-left: 15px;
          color: #27264d;
          font-weight: 500;
          font-size: 16px;
          line-height: 24px;
          letter-spacing: 0;
          opacity: 0.85;
        }

        .leftLi {
          display: flex;
          .circle {
            position: relative;
          }
          .circle::after {
            content: '';
            position: absolute;
            top: 60%;
            left: 50%;
            transform: translate(-50%, 0);
            width: 2px;
            height: var(--circle-height, 420px);
            background-color: #75b7ff;
          }
        }
        .leftLi2 {
          display: flex;
          margin-top: 400px;
          align-items: center;
          .textBottom {
            padding-left: 10px;
            color: rgba(112, 114, 121, 0.85);
            cursor: pointer;
            img {
              width: 15px;
              height: 12px;
            }
          }
        }
        .leftLi3 {
          display: flex;
          .circle3 {
            position: relative;
            top: var(--circle-top, 40px);
            opacity: var(--opacity, 0);
          }
        }
        .isCreateTrue {
          --circle-height: 560px;
          --circle-top: 110px;
          --opacity: 1;
        }
      }
    }
    .elForm {
      width: 1000px;

      .echarts {
        #myEcharts {
          width: 800px;
          height: 200px;
        }
      }

      .selectModel {
        margin-top: 20px;
      }

      :deep(.el-select) {
        width: 100%;
      }
      .elButton {
        :deep(.el-form-item__content) {
          display: flex;
          justify-content: space-evenly;
          margin-top: 20px;
        }
      }
    }
  }

  :deep(.el-card__body) {
    display: flex;
  }
}
</style>
